import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class InsertDemo {
    public static void main(String[] args) {
        int rs = InsertDemo.insert();
        if(rs > 0){
            System.out.println("添加用户成功！！");
        }else{
            System.out.println("添加用户失败！！！");
        }
    }

    public static int insert() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        int result = 0;
        try {
            // 1.加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2.获得连接
            String url = "jdbc:mysql://localhost:3306/jdbctest?zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai";
            String user = "root";
            String password = "root";
            conn = DriverManager.getConnection(url, user, password);
            // 3.执行insert操作
            // 3.1编写sql语句
            String sql = "insert into user values (null,'戴沐白','1234',24)";
            // 3.2获得执行sql的对象
            pstmt = conn.prepareStatement(sql);
            // 3.3执行sql语句
            result = pstmt.executeUpdate();
            // pstmt.executeUpdate(sql);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {//关闭连接
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                pstmt = null;
            }
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
